'use strict';

module.exports = options => {
  return async function jwt(ctx, next) {
    // 获取 token
    const token = ctx.request.header.authorization ? ctx.request.header.authorization.replace('Bearer ', '') : null;
    
    if (!token) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '未登录或登录已过期',
      };
      return;
    }
    
    try {
      // 解析token
      const decoded = ctx.app.jwt.verify(token, options.secret);
      ctx.state.user = decoded;
      await next();
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: '登录已过期，请重新登录',
        };
      } else {
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: '无效的token',
        };
      }
    }
  };
};
